package com.david.nacos.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author David
 * @version V1.0
 * @Package com.david.nacos.config
 * @date 2021/5/15 19:43
 */
public class QuickStart {
    public static void main(String[] args) throws NacosException, InterruptedException {
        //nacos服务地址
        String serverAddr = "192.168.219.104:8848";
        //dataId
        String dataId = "test";
        //group
        String group = "DEFAULT_GROUP";
        String namespace="10ab5c35-be99-438f-80ef-ec7146c61b04";
        //配置服务地址参数
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        //获取配置
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println("初始配置数据 = " + content);
        //监听配置
        configService.addListener(dataId, group, new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println("监听接受到数据:" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });
        //发布配置
        boolean isPublishOk = configService.publishConfig(dataId, group, "新发布的配置参数");
        System.out.println("新发布参数："+(isPublishOk?"成功！":"失败！"));
        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println("再次获取参数：" + content);
        //删除配置
        boolean isRemoveOk = configService.removeConfig(dataId, group);
        System.out.println("删除该配置"+(isRemoveOk?"成功！":"失败！"));
        Thread.sleep(3000);
        content = configService.getConfig(dataId, group, 5000);
        System.out.println("删除配置后获取配置：" + content);
    }
}
